export const fetchData = async (inputUrl, cmd, params, context) => {
  try {
    const queryParams = params
      .map(param => `params=${encodeURIComponent(param)}`)
      .join('&');
    let url = `${inputUrl}?cmd=${encodeURIComponent(cmd)}&${queryParams}`;
    if (context) {
      url = `${url}&context=${encodeURIComponent(context)}`;
    }
    //console.log('fetchData ', url);
    const response = await fetch(url);
    const data = await response.json();
    // 处理返回的数据
    //console.log(data);
    return data;
  } catch (error) {
    // 处理错误
    console.error(error);
    return undefined;
  }
};

export const bcos_rpc = async (cmd, params, context) => {
  if (params == undefined) {
    params = [];
  }
  var url = global.proxy_rpc_url;
  console.log(
    'bcos_rpc => global.proxy_rpc_url ',
    context,
    cmd,
    global.proxy_rpc_url,
  );
  var res = await fetchData(url, cmd, params);
  console.log('bcos_rpc => response ', context, cmd, res);
  return res;
};

export const bcos_raw = async (cmd, name, address, rawdata, params, abi) => {
  if (rawdata == undefined) {
    rawdata = '';
  }
  if (params == undefined) {
    params = [];
  }
  if (address == undefined) {
    address = '';
  }
  if (abi == undefined) {
    abi = '';
  }

  if (name == undefined) {
    name = '';
  }
  const queryParams = params
    .map(param => `params=${encodeURIComponent(param)}`)
    .join('&');
  var url = global.proxy_raw_url + `?cmd=${cmd}`;
  url = url + `&name=${name}`;
  url = url + `&address=${address}`;
  url = url + `&rawdata=${rawdata}`;
  url = url + `&abi=${encodeURIComponent(abi)}`;
  url = url + `&${queryParams}`;
  console.log('--bcos_raw url ', url);
  var response = await fetchData(url, cmd, params);
  console.log('>>>> bcos_raw response ', cmd, name, address, response);
  return response;
};
